<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文本转JSON数组工具</title>
    <link rel="stylesheet" href="styles.css">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        /* 示例文本样式 */
        .example-section {
            background-color: var(--tip-background);
            border: 1px solid var(--border-color);
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .example-section h3 {
            color: var(--primary-color);
            margin-bottom: 10px;
            font-size: 16px;
        }
        
        .example-text {
            font-family: 'Consolas', monospace;
            font-size: 13px;
            background-color: var(--card-background);
            padding: 10px;
            border-radius: 4px;
            border: 1px solid var(--border-color);
            white-space: pre-wrap;
            overflow-x: auto;
        }
        
        .use-example-btn {
            background-color: var(--secondary-color);
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            margin-top: 8px;
            transition: background-color 0.3s;
        }
        
        .use-example-btn:hover {
            background-color: var(--primary-color);
        }
        
        /* JSON输出样式 */
        .json-output {
            font-family: 'Consolas', monospace;
            font-size: 14px;
            line-height: 1.4;
            color: var(--text-color);
            background-color: var(--card-background);
            padding: 15px;
            border-radius: 4px;
            overflow: auto;
            white-space: pre-wrap;
            border: 1px solid var(--border-color);
            min-height: 200px;
        }
        
        .json-key {
            color: #0451a5;
            font-weight: bold;
        }
        
        [data-theme="dark"] .json-key {
            color: #9cdcfe;
        }
        
        .json-string {
            color: #a31515;
        }
        
        [data-theme="dark"] .json-string {
            color: #ce9178;
        }
        
        .json-number {
            color: #098658;
        }
        
        [data-theme="dark"] .json-number {
            color: #b5cea8;
        }
        
        .json-bracket {
            color: var(--text-color);
            font-weight: bold;
        }
        
        .stats-info {
            display: flex;
            gap: 20px;
            margin-bottom: 10px;
            font-size: 14px;
            color: var(--text-color);
        }
        
        .stats-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .stats-item i {
            color: var(--primary-color);
        }
        
        /* CSV输入框样式 - 与JSON输出保持一致 */
        #csv-input {
            font-family: 'Consolas', monospace;
            font-size: 14px;
            line-height: 1.4;
            color: var(--text-color);
            background-color: var(--card-background);
            padding: 15px;
            border-radius: 4px;
            border: 1px solid var(--border-color);
            height: 580px;
            width: 100%;
            box-sizing: border-box;
            resize: vertical;
            overflow: auto;
            white-space: pre-wrap;
        }
        
        #csv-input::placeholder {
            color: var(--text-color);
            opacity: 0.6;
            font-family: 'Consolas', monospace;
            font-size: 14px;
            line-height: 1.4;
        }
        
        #csv-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb), 0.2);
        }
    </style>
</head>
<body>
    <header>
        <div class="header-container">
            <div class="header-left">
                <div class="logo">
                    <span><a href="https://geekdaxue.co/" target="_blank"><img src="https://geekdaxue.co/static/images/logo_platypus.png" height="30px"></a></span>
                </div>
                <nav class="main-navigation">
                    <div class="nav-item dropdown">
                        <a href="#" class="nav-link">
                            JSON工具 <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="dropdown-menu">
                            <a href="../json/index.html">JSON 格式化</a>
                            <a href="../json/parser.html">JSON 格式校验</a>
                            <a href="../json/excel.html">JSON 转 Excel/CSV</a>
                            <a href="../json/jsonxml.html">JSON 与 XML 转换</a>
                            <a href="../json/editor.html">JSON 编辑器</a>
                            <a href="../json/txt2json_arr.html">文本转JSON数组</a>
                        </div>
                    </div>
                    <div class="nav-item dropdown">
                        <a href="#" class="nav-link">
                            编码转换 <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="dropdown-menu">
                            <a href="../coding/base64.html">Base64 编码</a>
                            <a href="../coding/urlencoding.html">URL 编码</a>
                            <a href="../coding/md5.html">MD5 加密</a>
                            <a href="../coding/unicode.html">Unicode 转换</a>
                            <a href="../coding/hex_convert.html">进制转换</a>
                        </div>
                    </div>
                    <div class="nav-item dropdown">
                        <a href="#" class="nav-link">
                            文本工具 <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="dropdown-menu">
                            <a href="../txt/diff.html">文本对比</a>
                            <a href="../txt/replace.html">文本替换</a>
                            <a href="../txt/remove.html">空白行移除</a>
                            <a href="../txt/cn_trans.html">繁简体转换</a>
                            <a href="../txt/html_format.html">HTML 格式化</a>
                            <a href="../txt/xml_format.html">XML 格式化</a>
                        </div>
                    </div>
                    <div class="nav-item dropdown">
                        <a href="#" class="nav-link">
                            图片工具 <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="dropdown-menu">
                            <a href="../img/2svg.html">图片转 SVG</a>
                            <a href="../img/qr_code.html">二维码生成</a>
                            <a href="../img/barcode.html">条形码生成</a>
                        </div>
                    </div>
                </nav>
            </div>
            <div class="header-controls">
                <div class="theme-toggle">
                    <input type="checkbox" id="theme-switch" class="theme-switch">
                    <label for="theme-switch" class="theme-switch-label">
                        <i class="fas fa-sun"></i>
                        <i class="fas fa-moon"></i>
                        <span class="slider"></span>
                    </label>
                </div>
                <div class="share-button" id="share-button" title="分享给朋友">
                    <i class="fas fa-share-alt"></i>
                    <span>分享</span>
                </div>
            </div>
        </div>
    </header>

    <div class="container">
        <h1>文本转JSON数组工具</h1>
        <div id="privacy-notice" class="privacy-notice">
            <div class="privacy-notice-content">
                <i class="fas fa-shield-alt"></i>
                <p>安全提示：您的数据仅在本地浏览器中处理，不会上传到服务器，请放心使用！</p>
                <button id="close-notice" class="close-notice" title="关闭提示">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
        
        <div class="example-section">
            <h3><i class="fas fa-lightbulb"></i> 使用说明</h3>
            <p>将CSV格式的文本转换为JSON数组。第一行为字段名称，后续行为数据行，字段间用英文逗号分隔。</p>
            <div class="example-text">id,name,age,city
"1","张三","25","北京"
"2","李四","30","上海"
"3","王五","28","广州"</div>
            <button class="use-example-btn" onclick="useExample()">使用此示例</button>
        </div>
        
        <main>
            <div class="editor-container">
                <div class="input-section">
                    <h2>输入CSV文本</h2>
                    <textarea id="csv-input" placeholder="请输入CSV格式的文本数据...&#10;第一行为字段名称，后续行为数据行&#10;例如：&#10;id,name,age&#10;&quot;1&quot;,&quot;张三&quot;,&quot;25&quot;&#10;&quot;2&quot;,&quot;李四&quot;,&quot;30&quot;"></textarea>
                    <div class="button-group">
                        <button id="convert-btn">转换为JSON</button>
                        <button id="clear-btn">清空</button>
                    </div>
                    <div id="error-message" class="error-message"></div>
                </div>
                
                <div class="output-section">
                    <div class="output-header">
                        <h2>JSON数组结果</h2>
                        <div class="output-buttons">
                            <div class="stats-info">
                                <div class="stats-item">
                                    <i class="fas fa-list"></i>
                                    <span id="record-count">记录数: 0</span>
                                </div>
                                <div class="stats-item">
                                    <i class="fas fa-columns"></i>
                                    <span id="field-count">字段数: 0</span>
                                </div>
                            </div>
                            <button id="copy-btn" class="copy-btn" title="复制到剪贴板">
                                <i class="fas fa-copy"></i> 复制
                            </button>
                        </div>
                    </div>
                    <div id="json-output" class="json-output"></div>
                </div>
            </div>
        </main>
    </div>
    
    <footer>
        <div class="footer-container">
            <div class="footer-main">
                <div class="footer-section about-us">
                    <h3>关于我们</h3>
                    <p>我们提供一系列高效、便捷的在线工具，帮助开发者、非技术人员提高工作效率，解决日常开发中遇到的各种问题。</p>
                    <p>Build With <i class="fa-solid fa-heart" style="color: red;"></i> For SF.</p>
                </div>
                <div class="footer-section links">
                    <h3>工具导航</h3>
                    <div class="links-columns">
                        <ul>
                            <li><a href="../json/index.html">JSON 工具</a></li>
                            <li><a href="../img/index.html">图片处理</a></li>
                            <li><a href="#">开发工具</a></li>
                        </ul>
                        <ul>
                            <li><a href="../coding/index.html">编码转换</a></li>
                            <li><a href="../txt/index.html">文本工具</a></li>
                        </ul>
                    </div>
                </div>
                <div class="footer-section contact">
                    <h3>联系我们</h3>
                    <div class="social-icons">
                        <a href="#" title="GitHub"><i class="fab fa-github"></i></a>
                        <a href="#" title="Twitter"><i class="fab fa-twitter"></i></a>
                        <a href="#" title="WeChat"><i class="fab fa-weixin"></i></a>
                        <a href="mailto:example@example.com" title="Email"><i class="fas fa-envelope"></i></a>
                    </div>
                    <p>如有问题或建议，请随时联系我们</p>
                </div>
            </div>
            <div class="footer-bottom">
                <p>© 2025 文本转JSON数组工具. 保留所有权利</p>
                <div class="footer-legal">
                    <a href="#">使用条款</a>
                    <a href="#">隐私政策</a>
                </div>
            </div>
        </div>
    </footer>
    
    <div id="copy-notification" class="copy-notification">已复制到剪贴板！</div>
    <div id="share-notification" class="copy-notification">已复制网址，赶快让更多的小伙伴知道我吧！</div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            const csvInput = document.getElementById('csv-input');
            const jsonOutput = document.getElementById('json-output');
            const convertBtn = document.getElementById('convert-btn');
            const clearBtn = document.getElementById('clear-btn');
            const copyBtn = document.getElementById('copy-btn');
            const errorMessage = document.getElementById('error-message');
            const copyNotification = document.getElementById('copy-notification');
            const shareNotification = document.getElementById('share-notification');
            const themeSwitch = document.getElementById('theme-switch');
            const privacyNotice = document.getElementById('privacy-notice');
            const closeNoticeBtn = document.getElementById('close-notice');
            const shareButton = document.getElementById('share-button');
            const recordCount = document.getElementById('record-count');
            const fieldCount = document.getElementById('field-count');
            
            // 检查本地存储中的主题设置
            if (localStorage.getItem('theme') === 'dark') {
                document.documentElement.setAttribute('data-theme', 'dark');
                themeSwitch.checked = true;
            }
            
            // 主题切换功能
            themeSwitch.addEventListener('change', function() {
                if (this.checked) {
                    document.documentElement.setAttribute('data-theme', 'dark');
                    localStorage.setItem('theme', 'dark');
                } else {
                    document.documentElement.removeAttribute('data-theme');
                    localStorage.setItem('theme', 'light');
                }
            });
            
            // 隐私提示框关闭功能
            closeNoticeBtn.addEventListener('click', function() {
                privacyNotice.style.display = 'none';
                localStorage.setItem('privacyNoticeClosed', 'true');
            });
            
            // 检查是否需要显示隐私提示
            if (localStorage.getItem('privacyNoticeClosed') === 'true') {
                privacyNotice.style.display = 'none';
            }
            
            // 分享功能
            shareButton.addEventListener('click', function() {
                const url = window.location.href;
                navigator.clipboard.writeText(url).then(function() {
                    showNotification(shareNotification);
                }).catch(function() {
                    console.error('复制失败');
                });
            });
            
            // CSV解析函数
            function parseCSV(text) {
                const lines = text.trim().split('\n');
                if (lines.length < 2) {
                    throw new Error('至少需要包含标题行和一行数据');
                }
                
                const result = [];
                const headers = parseCSVLine(lines[0]);
                
                for (let i = 1; i < lines.length; i++) {
                    const line = lines[i].trim();
                    if (line) {
                        const values = parseCSVLine(line);
                        if (values.length !== headers.length) {
                            throw new Error(`第${i + 1}行的字段数量与标题行不匹配`);
                        }
                        
                        const obj = {};
                        for (let j = 0; j < headers.length; j++) {
                            obj[headers[j]] = values[j];
                        }
                        result.push(obj);
                    }
                }
                
                return { data: result, headers: headers };
            }
            
            // 解析CSV行（处理引号）
            function parseCSVLine(line) {
                const result = [];
                let current = '';
                let inQuotes = false;
                let i = 0;
                
                while (i < line.length) {
                    const char = line[i];
                    
                    if (char === '"') {
                        if (inQuotes && line[i + 1] === '"') {
                            // 转义的引号
                            current += '"';
                            i += 2;
                        } else {
                            // 切换引号状态
                            inQuotes = !inQuotes;
                            i++;
                        }
                    } else if (char === ',' && !inQuotes) {
                        // 字段分隔符
                        result.push(current.trim());
                        current = '';
                        i++;
                    } else {
                        current += char;
                        i++;
                    }
                }
                
                // 添加最后一个字段
                result.push(current.trim());
                
                return result;
            }
            
            // 格式化JSON输出
            function formatJSON(obj) {
                return JSON.stringify(obj, null, 2);
            }
            
            // 语法高亮
            function highlightJSON(json) {
                return json
                    .replace(/(".*?")\s*:/g, '<span class="json-key">$1</span>:')
                    .replace(/:\s*(".*?")/g, ': <span class="json-string">$1</span>')
                    .replace(/:\s*(\d+)/g, ': <span class="json-number">$1</span>')
                    .replace(/[\[\]{}]/g, '<span class="json-bracket">$&</span>');
            }
            
            // 转换功能
            convertBtn.addEventListener('click', function() {
                const inputText = csvInput.value.trim();
                
                if (!inputText) {
                    showError('请输入CSV文本数据');
                    return;
                }
                
                try {
                    const parsed = parseCSV(inputText);
                    const jsonString = formatJSON(parsed.data);
                    const highlightedJSON = highlightJSON(jsonString);
                    
                    jsonOutput.innerHTML = highlightedJSON;
                    
                    // 更新统计信息
                    recordCount.textContent = `记录数: ${parsed.data.length}`;
                    fieldCount.textContent = `字段数: ${parsed.headers.length}`;
                    
                    hideError();
                } catch (error) {
                    showError('解析错误: ' + error.message);
                    jsonOutput.innerHTML = '';
                    recordCount.textContent = '记录数: 0';
                    fieldCount.textContent = '字段数: 0';
                }
            });
            
            // 清空功能
            clearBtn.addEventListener('click', function() {
                csvInput.value = '';
                jsonOutput.innerHTML = '';
                recordCount.textContent = '记录数: 0';
                fieldCount.textContent = '字段数: 0';
                hideError();
            });
            
            // 复制功能
            copyBtn.addEventListener('click', function() {
                const outputText = jsonOutput.textContent;
                if (!outputText) {
                    showError('没有可复制的内容');
                    return;
                }
                
                navigator.clipboard.writeText(outputText).then(function() {
                    showNotification(copyNotification);
                }).catch(function() {
                    // 降级方案
                    const textArea = document.createElement('textarea');
                    textArea.value = outputText;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    showNotification(copyNotification);
                });
            });
            
            // 显示错误信息
            function showError(message) {
                errorMessage.textContent = message;
                errorMessage.style.display = 'block';
            }
            
            // 隐藏错误信息
            function hideError() {
                errorMessage.style.display = 'none';
            }
            
            // 显示通知
            function showNotification(notification) {
                notification.classList.add('show');
                setTimeout(function() {
                    notification.classList.remove('show');
                }, 2000);
            }
        });
        
        // 使用示例功能
        function useExample() {
            const exampleText = `id,name,age,city
"1","张三","25","北京"
"2","李四","30","上海"
"3","王五","28","广州"`;
            document.getElementById('csv-input').value = exampleText;
        }
    </script>
</body>
</html>